'use strict';
const appid = "wxb562a369c3c80db6"; //小程序appId
const secret = "22fd724a6e3af51c7ea1e5c5473bf774"; //小程序secret
const touser = "oINcf5oPDbnmpTEcSIOV0gxK8Zaw"; //发送人
const template_id = "JrVpQPj_SNzJorhL2UcZER1B6INT7HNAanX5ywxjbCw"; //模板ID
const template_id_night = "hn4dEoyJt1k_kCduk5-H2vXeXsJ5xUxbo_PiLMarIIc"; //下午信息模板ID---根据需求填写，不需要请清空
const lianAi_date = "1970-01-01"; //恋爱日期
const birthday_date = "2001-11-01"; //生日
const cityName = "北京"; //城市
const weather_appId = "lhcqhpmvspggdpiq"; //天气api秘钥-不用改
const weather_app_secret = "cUtwcDVnQTkwdXBaRm81cEEraDd2QT09"; //天气api秘钥-不用改

exports.main = async () => {
	/**
	 * 这里指定了就是一个人，为空则是所有人
	 */
	let to_user = touser;//一个人
	//let to_user = null;//关注的所有人发送
	console.log("当前服务器处理后时间", getDate())
	//获取token
	let token = await getToken();
	//获取天气
	let weather = await getWeather(cityName);
	console.log(weather)
	let forecasts = weather.data.forecasts[0];
	forecasts['address'] = weather.data.address
	forecasts['cityCode'] = weather.data.cityCode
	//接口限制
	sleep(1000);
	//获取每日一句话
	let content = await getRecommend();
	content = content.data[0]['content']
	//推送模板消息-to_user不为空时，指定用户，否则所有用户
	if (to_user) {
		let res = await push(forecasts, content, token, to_user);
		console.log("发送指定用户完成：",to_user)
	} else {
		let {data} = await getUserAll(token.access_token);
		console.log("获取所有用户：",data.openid);
		
		data.openid.forEach(function (value, index) {
		   push(forecasts, content, token, value)
		   console.log("发送指定用户" +value + "完成")
		});
	}
	 return "ok";
};



/**
 * 推送模板消息
 */
function push(forecasts, content, token, to_user) {
	var data = JSON.stringify({
		"touser": to_user,
		"template_id": isMoring()?template_id:(template_id_night?template_id_night:template_id),
		"topcolor": "#FF0000",
		"data": {
			"date": {
				"value": forecasts.date + " " + getDayOfWeek(forecasts.dayOfWeek),
				"color": "#00BFFF"
			},
			"city": {
				"value": forecasts.address,
				"color": "#173177"
			},
			"weather": {
				"value": forecasts.dayWeather + '转' + forecasts.nightWeather,
				"color": "#EE212D"
			},
			"min_temperature": {
				"value": forecasts.nightTemp,
				"color": "#FF6347"
			},
			"max_temperature": {
				"value": forecasts.dayTemp,
				"color": "#42B857"
			},
			"love_day": {
				"value": calculationLianAi(lianAi_date),
				"color": "#B95EA3"
			},
			"birthday": {
				"value": calculationBirthday(birthday_date),
				"color": "#FF69B4"
			},
			"content": {
				"value": content,
				"color": "#C71585"
			},
		}
	});
	var config = {
		method: 'post',
		headers: {
			'Content-Type': 'application/json'
		},
		data: data
	};
	return httpRequest("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token.access_token,
		config);
}
/**
 * 获取所有用户
 */
function getUserAll(access_token) {
	return httpRequest("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + access_token);
}

/**
 * 获取token
 */
function getToken() {
	return httpRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid +
		"&secret=" + secret);
}
/**获取天气
 * @param {Object} cityName
 */
function getWeather(cityName) {
	return httpRequest("https://www.mxnzp.com/api/weather/forecast/" + cityName + "?app_id=" + weather_appId +
		"&app_secret=" + weather_app_secret);
}
/**
 * 获取每日一句话
 */
function getRecommend() {
	return httpRequest("https://www.mxnzp.com/api/daily_word/recommend?count=1&app_id=" + weather_appId +
		"&app_secret=" + weather_app_secret);
}
/**
 * 计算生日
 * @param {Object} birthday
 */
function calculationBirthday(birthday) {
	var daysTotal = 0;
	var date = getDate();
	var year = date.getFullYear(); //当前年份
	var _month = date.getMonth() + 1; //当前月份
	var _day = date.getDate(); //当前天数
	var month = parseInt(birthday.split('-')[1]);
	//生日月份
	var day = parseInt(birthday.split('-')[2]);
	//生日天数
	if (month > _month) {
		for (var j = _month; j < month; j++) {
			daysTotal = TotalDays(year, j, daysTotal);
		}
		daysTotal = daysTotal + day - _day;
	} else if (month < _month) {
		for (var k = month; k < _month; k++) {
			daysTotal = TotalDays(year, k, daysTotal);
		}
		var dayFull = TotalDays(year, 0, daysTotal);
		daysTotal = dayFull - daysTotal + day - _day;
	} else {
		if (day >= _day) {
			daysTotal = day - _day;
		} else {
			daysTotal = TotalDays(year, 0, daysTotal) - (_day - day);
		}
	}
	return daysTotal;
}
/**
 * 计算恋爱
 * @param {Object} lianAi_date
 */
function calculationLianAi(lianAi_date) {
	var new_date = getDate(); //新建一个日期对象，默认现在的时间
	var old_date = new Date(lianAi_date + " 00:00:00"); //设置过去的一个时间点，"yyyy-MM-dd HH:mm:ss"格式化日期
	var difftime = (new_date - old_date) / 1000; //计算时间差,并把毫秒转换成秒
	var days = parseInt(difftime / 86400); // 天  24*60*60*1000 
	return days;
}
/**
 * 接口限制需睡眠一秒
 * @param {Object} numberMillis
 */
function sleep(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return true;
	}
}
//JS判断闰年代码
function isLeapYear(Year) {
	if (((Year % 4) == 0) && ((Year % 100) != 0) || ((Year % 400) == 0)) {
		return (true);
	} else {
		return (false);
	}
}
//判断上午下午
function isMoring() {
	var date= getDate();
	let hours = date.getHours();
	return hours<12;
}
//获取当前时间,根据时区偏移判断是否需要加8小时
function getDate(){
	var date= new Date();
	let hours = date.getHours();
	if(date.getTimezoneOffset()>=0){
		date.setHours(hours+8);
	}
	return date;
}

/**
 * 发送请求
 * @param {Object} url
 * @param {Object} config
 */
function httpRequest(url, config) {
	let res = uniCloud.httpclient.request(url, config ? config : null);
	return new Promise(function(resolve) {
		res.then(ress => {
			let arrayBuffer = ress.res.data
			let unit8Arr = new Uint8Array(arrayBuffer)
			let encodedString = String.fromCharCode.apply(null, unit8Arr)
			let decodedString = decodeURIComponent(escape(encodedString))
			let data = JSON.parse(decodedString)
			resolve(data)
		})
	})
}
/**
 * 获取星期
 * @param {Object} iWeek
 */
function getDayOfWeek(iWeek) {
	if (iWeek == 0) iWeek = '星期日';
	if (iWeek == 1) iWeek = '星期一';
	if (iWeek == 2) iWeek = '星期二';
	if (iWeek == 3) iWeek = '星期三';
	if (iWeek == 4) iWeek = '星期四';
	if (iWeek == 5) iWeek = '星期五';
	if (iWeek == 6) iWeek = '星期六';
	if (iWeek == 7) iWeek = '星期日';
	return iWeek;
}

function TotalDays(year, month, days) {
	switch (month) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			days += 31;
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			days += 30;
			break;
		case 2:
			if (isLeapYear(year)) {
				days += 29;
			} else {
				days += 28;
			}
			break;
		default:
			if (isLeapYear(year)) {
				days = 366;
			} else {
				days = 365;
			}
			break;
	}
	return days;
}
